package netty.demo_05_GroupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Netty应用实例-群聊系统
 * 服务端
 *
 * @author chenyuan
 * @date 2020/11/9 16:11
 */
public class ChatServer {
	// 端口
	private int port;

	/**
	 * 构造器
	 */
	public ChatServer(int port) {
		this.port = port;
	}

	/**
	 * 处理客户端的请求
	 */
	public void run() throws InterruptedException {
		// 创建两个线程组
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);

		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();

			serverBootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 128)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							// 获取 Pipeline
							ChannelPipeline pipeline = socketChannel.pipeline();
							// 通过 Pipeline 添加编、解码器（Netty 自带）
							pipeline.addLast("decoder", new StringDecoder());
							pipeline.addLast("encoder", new StringEncoder());
							// 加入自己的 Handler
							pipeline.addLast(new ChatServerHandler());
						}
					});

			System.out.println("服务端准备完毕");
			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new ChatServer(8000).run();
	}
}
